package com.asimplefox.filter;

import com.asimplefox.entity.Role;
import com.asimplefox.entity.Vid;
import com.asimplefox.entity.Visitor;
import com.asimplefox.serurity.TokenManager;
import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.service.IRoleService;
import com.asimplefox.service.IVidService;
import com.asimplefox.service.IVisitorService;
import com.asimplefox.service.abst.ResultU;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import static com.asimplefox.filter.RedirectFilter.SF_0;
import static com.asimplefox.filter.RedirectFilter.getOsName;

@WebFilter(filterName = "resFilter", urlPatterns = "/videos/**")
@Slf4j
public class ResFilter implements Filter, ResultU {

    @Autowired
    TokenManager tokenManager;

    @Autowired
    IRoleService roleService;

    @Autowired
    IVidService vidService;

    @Autowired
    IVisitorService visitorService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        requestURI = URLDecoder.decode(requestURI, "utf-8");
        boolean check = PATH_MATCHER.match("/videos/**/**.jpg", requestURI);
        if (check) {
            log.debug("本次请求{}不需要处理", request.getRequestURI());
        } else {
            if (PATH_MATCHER.match("/videos/**", requestURI)) {
                String sukey = requestURI;
                if (!requestURI.endsWith("mp4")) {
                    sukey = requestURI.substring(0, requestURI.lastIndexOf(".")) + ".mp4";
                }
                Vid vid = vidService.lambdaQuery().likeLeft(Vid::getUrl, sukey).one();
                if (vid == null) {
                    log.debug("{} 放行", requestURI);
                } else if (vid.getAstrict()) {
                    UserRoleDetails userDetails = tokenManager.getContextUserDetail(request);
                    if (userDetails == null) {
                        response.getWriter().write(define("please login."));
                        return;
                    }
                    List<Role> roles = roleService.lambdaQuery().eq(Role::getUserId, userDetails.getUser().getId()).list();
                    if (!hasRoleAny(roles, TokenManager.ADMIN, TokenManager.VIP)) {
                        response.getWriter().write(define("Please open VIP to access"));
                        return;
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
        return;
    }

    private boolean hasRoleAny(List<Role> roles, String... rs) {
        for (Role role : roles) {
            for (String r : rs) {
                if (r.equalsIgnoreCase(role.getUserRole())) {
                    return true;
                }
            }
        }
        return false;
    }


    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
}
